<template>
    <j-modal
      width="80%"
      :title="title"
      :maskClosable="false"
      :switchFullscreen="true"
      :destroyOnClose="true"
      :visible.sync="editModalVisible"
      @cancel="handleCancleDbSync"
    >
    <template slot="footer">
      <a-button @click="handleCancleDbSync">
        关闭
      </a-button>
      <a-button type="primary" :loading="syncLoading" @click="handleDbSync">确认</a-button>
    </template>
    <div class="table-page-search-wrapper warp">
      <a-form-model layout="horizontal" labelAlign="right" ref="ruleForm" :label-col="labelCol" :wrapper-col="wrapperCol" :model="formData" :rules="rules">
        <a-row :gutter="24">
          <a-col :xl="8" :lg="8" :md="8" :sm="24" >
            <a-form-model-item label="项目编码" prop="itemCode">
              <a-input :disabled="disableSubmit" v-model="formData.itemCode" placeholder="请输入任务编码"/>
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" >
            <a-form-model-item label="项目名称" prop="itemName">
              <a-input :disabled="disableSubmit" v-model="formData.itemName" placeholder="请输入项目名称"/>
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24">
            <a-form-model-item label="核算周期" prop="accountCycle">
              <j-dict-select-tag
                :disabled="disableSubmit"
                v-model="formData.accountCycle"
                placeholder="请选择项目类型"
                dict-code="hr_account_cycle"
              >
              </j-dict-select-tag>
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24">
            <a-form-model-item prop="attendanceScale" label="考勤比例（>=）">
              <a-input v-model="formData.attendanceScale" type="number" placeholder="请输入考勤比例（>=）"/>
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24">
            <a-form-model-item label="计算试用期比例">
              <j-dict-select-tag
                v-model="formData.isProbation"
                placeholder="请选择"
                dict-code="yes_no"
              >
              </j-dict-select-tag>
            </a-form-model-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" >
            <a-form-model-item label="是否计算绩效">
              <j-dict-select-tag
                v-model="formData.isPerformance"
                placeholder="请选择"
                dict-code="yes_no"
              >
              </j-dict-select-tag>
            </a-form-model-item>
          </a-col>
          <a-col :xl="16" :lg="16" :md="16" :sm="24">
            <a-form-model-item :label-col="{span: 3}" :wrapper-col="{span: 21}" label="备注">
              <a-textarea v-model="formData.remarks" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <vxe-grid
        ref="xTable"
        border
        resizable
        max-height="400px"
        keep-source
        :columns="column"
        :data="tableData"
        :edit-rules="validRules"
        :edit-config="{trigger: 'click', mode: 'row',showStatus: true}"
      >
        <template #calculationType="{ row }">
          <j-dict-select-tag
            @change="$refs.xTable.updateStatus(scope)"
            v-model="row.calculationType"
            placeholder="请选择"
            dict-code="hr_calculation_type"
          >
          </j-dict-select-tag>
        </template>
        <template #calculationTypeText="{ row }">
          <span>{{ getText('hr_calculation_type',row.calculationType) }}</span>
        </template>
        <template #disabledText="{ row }">
          <span>{{ getText('yes_no',row.disabled) }}</span>
        </template>
        <template #disabled="{ row }">
          <j-dict-select-tag
            @change="$refs.xTable.updateStatus(scope)"
            v-model="row.disabled"
            placeholder="请选择"
            dict-code="yes_no"
          >
          </j-dict-select-tag>
        </template>
      </vxe-grid>
    </div>
  </j-modal>
</template>
<script>
import { postAction, putAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import { initDictOptions, filterDictTextByCache } from '@/components/dict/JDictSelectUtil'
export default {
  name: 'SalaryItemsModal',
  data() {
    return {
      editModalVisible: false,
      disableSubmit: false,
      title: '新增',
      rules: {
        itemName: [
          { required: true, message: '请输入项目名称', trigger: 'blur' }
        ],
        itemCode: [
          { required: true, message: '请输入项目编码', trigger: 'blur' },
          { validator: (rule, value, callback) => validateDuplicateValue('hr_salary_item', 'item_code', value, this.formData.id, callback) }
        ],
        accountCycle: [
          { required: true, message: '请选择核算周期', trigger: 'blur' }
        ],
        attendanceScale: [
          { pattern: /^100$|^(\d|[1-9]\d)(\.\d+)*$/, message: '请输入0-100的数字' }
        ]
      },
      formData: {},
      syncLoading: false,
      url: {
        add: '/hr/salary/item/add',
        edit: '/hr/salary/item/edit',
        queryById: '/hr/salary/attendance/list'
      },
      column: [
        { type: 'seq', width: 60 },
        { title: '考勤事件', field: 'ruleType', slots: { default: ({ row }) => {
          return filterDictTextByCache('hr_attendance_events', row.ruleType)
        } }},
        { title: '是否启用', field: 'disabled', editRender: {}, slots: { edit: 'disabled', default: 'disabledText' }},
        { title: '计算方式', field: 'calculationType', editRender: {}, slots: { edit: 'calculationType', default: 'calculationTypeText' }},
        { title: '权重', field: 'weight', editRender: { name: '$input', props: { type: 'number' }}}
      ],
      tableData: [],
      dictOptions: {
        hr_attendance_events: []
      },
      validRules: {
        weight: [
          { min: 0, type: 'number', message: '请填写大于0的数字' },
          { validator: this.weightValid }
        ],
        calculationType: [
          { validator: this.calculationTypeValid }
        ]
      },
      labelCol: { span: 6 },
      wrapperCol: { span: 18 }
    }
  },
  methods: {
    weightValid({ cellValue, row }) {
      if (!cellValue && row.disabled === '1') {
        return new Error('请填写计算方式')
      }
    },
    calculationTypeValid({ cellValue, row }) {
      if (!cellValue && row.disabled === '1') {
        return new Error('请选择计算方式')
      }
    },
    handleCancleDbSync() {
      this.disableSubmit = false
      this.$refs['ruleForm'].resetFields()
      this.editModalVisible = false
    },
    add() {
      this.formData = {}
      this.initDictConfig('add')
      this.editModalVisible = true
    },
    edit(data) {
      this.initDictConfig()
      this.formData = JSON.parse(JSON.stringify(data))
      this.editModalVisible = true
      this.getAttendanceRules(data.itemCode)
    },
    getAttendanceRules(itemCode) {
      getAction(this.url.queryById, { itemCode: itemCode }).then(res => {
        if (res.success) {
          this.tableData = res.result
        } else {
          this.$message.warning(res.message)
          this.tableData = []
        }
      })
    },
    async handleDbSync() {
      Promise.all([
        this.$refs.xTable.fullValidate(),
        this.$refs['ruleForm'].validate()
      ]).then((res) => {
        this.updateData()
      }).catch(function(reason) {
        console.log(reason)
      })
    },
    updateData() {
      this.syncLoading = true
      const { fullData } = this.$refs.xTable.getTableData()
      this.formData.attendanceRules = fullData
      if (this.formData.id) {
        putAction(this.url.edit, this.formData).then(res => {
          this.actionSuccess(res)
        })
      } else {
        postAction(this.url.add, this.formData).then(res => {
          this.actionSuccess(res)
        })
      }
    },
    actionSuccess(res) {
      this.syncLoading = false
      if (res.success) {
        this.$emit('ok')
        this.editModalVisible = false
      } else {
        this.$message.warning(res.message)
      }
    },
    initDictConfig(type) { // 新增时请求薪资设置
      initDictOptions('hr_attendance_events').then((res) => {
        if (res.success) {
          this.dictOptions.hr_attendance_events = res.result
          if (type === 'add') {
            this.setTableData()
          }
        }
      }).catch(function(reason) {
        console.log(reason)
      })
    },
    setTableData() {
      this.tableData = []
      this.dictOptions['hr_attendance_events'].forEach(item => {
        this.tableData.push({
          ruleType: item.value,
          disabled: '0',
          weight: 1
        })
      })
    },
    getText(dictCode, val) {
      return filterDictTextByCache(dictCode, val)
    }
  }
}
</script>
<style lang="less">

</style>
